<template>
  <div class="photo">
    <img :src="imgSrc" ref="img">
    <div class="bottom">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="submit">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import {editPhotoAPI} from '@/api'
export default {
name: 'ModifyPhoto',
props:{
  imgSrc:{
    type: String,
    required: true
  }
},
data(){
  return {
    cropper: null
  }
},
methods:{
  submit(){
    this.$toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: '保存中',
    })
    console.log(this.cropper.getData());
    this.cropper.getCroppedCanvas().toBlob(async blob => {
      console.log(blob);
      const formData = new FormData()
      formData.append('photo', blob)
      try {
        const {data:{data:{photo}}} = await editPhotoAPI(formData)
        //关闭弹出
        this.$emit('close')
        this.$emit('updateSuccess',photo)
        this.$toast.success('保存成功')
      } catch (error) {
        console.log(error);
        this.$toast.fail('数据操作失败，请稍后重试！')
      }
    })
  }
},
mounted(){
  const image = this.$refs.img
  this.cropper = new Cropper(image, {
  dragMode: 'move',
  aspectRatio: 1,
  //背景图片
  background: false,
  //控制图片移动
  movable: true,
  //拖拽盒子的大小比例
  autoCropArea: 1,
  //控制拖拽盒子的移动
  cropBoxMovable: false,
  //控制拖拽盒子的缩放
  cropBoxResizable: false
})
}
}
</script>

<style scoped lang="less">
.photo {
  background-color: #000;
  display: flex;
  align-items: center;
  height: 100%;
  img {
    display: block;
    max-width: 100%;
    height: unset;
  }
  .bottom{
    position: fixed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    bottom: 0;
    left: 0;
    right: 0;
    font-size: 30px;
    color: #fff;
    div{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 120px;
      height: 120px;
    }
  }
}
</style>